import type { App } from "vue";
import { h, render } from "vue";
import * as Elicons from "@element-plus/icons-vue";
const icons: any = Elicons;
export default function setGlobalDirective(app: App<Element>) {
  //自定义loading
  app.directive("customLoading", {
    mounted(el, binding) {},
  });
  //自定义渲染elementPlus图标
  app.directive("icon", {
    mounted(el, binding) {
      let vnode: any;
      // updateIcon(binding.value);

      function updateIcon(newValue: any) {
        if (vnode) {
          // 销毁之前的渲染结果
          render(null, el);
        }
        if (newValue) {
          vnode = h(icons[newValue]);
          render(vnode, el);
        }
      }
      // 初始化
      updateIcon(binding.value);

      // 监听属性变化
      binding.instance!.$watch(() => binding.value, updateIcon);
    },
    updated(el, binding) {
      // 当组件更新时重新渲染图标
      if (binding.oldValue !== binding.value) {
        const vnode = h(icons[binding.value]);
        render(vnode, el);
      }
    },
  });

  // 全局图片加载失败自动降级指令
  app.directive("imgFallback", {
    mounted(el, binding) {
      el.onerror = () => {
        if (el.src !== binding.value) {
          el.src = binding.value;
        }
      };
      // 如果初始就加载失败，手动触发一次
      if (!el.complete || el.naturalWidth === 0) {
        el.src = binding.value;
      }
    },
    updated(el, binding) {
      el.onerror = () => {
        if (el.src !== binding.value) {
          el.src = binding.value;
        }
      };
    },
  });
}
